package com.example.shushiyunsst.fragment.main.home.child.icon_sst

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.arch.core.executor.ArchTaskExecutor
import com.alibaba.fastjson.JSON
import com.example.library_common.base.BaseDataBindingFragment
import com.example.library_common.glidmodule.GlideApp
import com.example.library_common.global.AppGlobals
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.OnTextListener
import com.example.library_common.utils.even.MessageWrap
import com.example.library_common.utils.even.TO_REFRESH_BALANCE_INFO
import com.example.library_common.utils.timer.BaseTimerTask
import com.example.library_common.utils.timer.ITimerListener
import com.example.shushiyunsst.R
import com.example.shushiyunsst.databinding.CurrencyTransferBuyFragmentBinding
import com.example.shushiyunsst.fragment.getUserBalanceInfo
import com.example.shushiyunsst.fragment.main.home.child.icon_sst.bean.*

import com.example.shushiyunsst.util.PayingPassWordVerifyPop
import com.example.shushiyunsst.util.push.helper.PushHelper
import com.example.wallet.db.BalanceInfoManager
import com.example.wallet.db.UserInfoManager
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.SimpleCallback
import kotlinx.android.synthetic.main.miner_fragment.*
import java.util.*

/**
 * 买出
 * */
class CurrencyTransferBuyFragment : BaseDataBindingFragment<CurrencyTransferBuyFragmentBinding>(),
    View.OnClickListener, ITimerListener, OnTextListener {

    companion object {
        fun newInstance(txId: String): CurrencyTransferBuyFragment {
            val args = Bundle()
            args.putString("txId", txId)

            val fragment = CurrencyTransferBuyFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private var mTimerTask: BaseTimerTask? = null

    private var mTimer: Timer? = null

    private var timer = 30

    private val handler: Handler = Handler(Looper.getMainLooper())

    private var txId: String? = ""

//    private var uid:String?=""

    private var bean: CurrencyTransferBean? = null

    private lateinit var mToolbar: Toolbar

    private var inputValue = ""

    private var sst=AppGlobals.getApplication().getString(R.string.wallet_sst)

    private var cml=AppGlobals.getApplication().getString(R.string.wallet_cml)

    private var cny = AppGlobals.getApplication().getString(R.string.wallet_cny)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        txId = arguments?.getString("txId")
//        uid=arguments?.getString("uid")
    }

    override fun layoutId(): Int {
        return R.layout.currency_transfer_buy_fragment
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mToolbar = view.findViewById(R.id.mToolbar)
//        mToolbar.title = "购买SST"
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }

        viewBinder.onViewClick = this
        viewBinder.onTextListener = this

        viewBinder.mProgressBar.visibility = View.VISIBLE

        val map = mapOf(
            "txid" to txId
        )
        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.queryTokenTxByTxid)
            .success {

                parseQueryTokenTxByTxId(it)
                viewBinder.mProgressBar.visibility = View.GONE
                mToolbar.title = "购买 ${bean?.tokenType?.toUpperCase()}"
            }
            .failure {
                Toast.makeText(_mActivity, "获取商家信息失败", Toast.LENGTH_SHORT).show()
                onBackPressedSupport()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
                onBackPressedSupport()
            }
            .build()
            .post()


    }


    private fun parseQueryTokenTxByTxId(it: String?) {
        val obj = JSON.parseObject(it)
        val tokenTx = obj["tokenTx"]?.toString() ?: ""
        bean = JSON.parseObject(tokenTx, CurrencyTransferBean::class.java)
        viewBinder.bean = bean

        presentBalance()

        GlideApp.with(this)
            .load(bean?.userLogo)
            .centerCrop()
            .into(viewBinder.icon)

    }

    override fun handMessage(msg: MessageWrap?) {
        super.handMessage(msg)
        if (msg?.message == TO_REFRESH_BALANCE_INFO) {
            presentBalance()
        }
    }

    @SuppressLint("SetTextI18n")
    private fun presentBalance() {
        when(bean?.tokenType){
            sst->{
                viewBinder.mainIcon.visibility=View.VISIBLE
                viewBinder.cancelTv.visibility=View.VISIBLE
                viewBinder.motherIconCml.visibility=View.GONE
                viewBinder.priceUnit.text="价格\t$cny"
                startTimer()
                viewBinder.takeOrder.text="下单"
                viewBinder.tipTv.visibility=View.VISIBLE
            }
            cml->{
                viewBinder.priceUnit.text="价格\t$sst"
                viewBinder.cancelTv.visibility=View.GONE
                viewBinder.mainIcon.visibility=View.GONE
                viewBinder.motherIconCml.visibility=View.VISIBLE
                val balanceInfo = BalanceInfoManager.mBalanceInfoManager.getBalanceInfoBean()?.balanceInfo
                viewBinder.titleTemplate.text="当前${sst}余额"
                viewBinder.moneyTv.text= "${balanceInfo?.sstBalance}"
                viewBinder.takeOrder.text="下单并支付"
                viewBinder.tipTv.visibility=View.GONE
            }
        }
    }



    private fun startTimer() {
        if (mTimerTask !== null) return


        mTimer = Timer()

        mTimerTask = BaseTimerTask(this)
        mTimer?.schedule(mTimerTask, 1000, 1000)
    }

    private fun stopTimer() {


        if (mTimer != null) {
            mTimer?.cancel()
            mTimer = null
        }

        if (mTimerTask != null) {
            mTimerTask?.cancel()
            mTimerTask = null
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.take_order -> {

                if (TextUtils.isEmpty(inputValue)) {
                    Toast.makeText(_mActivity, "请输入交易金额", Toast.LENGTH_SHORT).show()
                    return
                }
                val inputValue = inputValue.toDouble()
                val limitMin = bean?.limitMin?.toDouble() ?: 0.0
                val limitMax = bean?.limitMax?.toDouble() ?: 0.0
                if(inputValue in limitMin..limitMax){
                    when(bean?.tokenType){
                        sst->{
//                            showBuyingPop()
                            buyingSSTNow()
                        }
                        cml->{
                            showBuyingPop()
//                            buyingCMLNow()
                        }
                    }

                }else{
                    Toast.makeText(_mActivity, "交易金额必须在${bean?.limitMin} ~ ${bean?.limitMax}之间", Toast.LENGTH_SHORT).show()
                }

            }
            R.id.forAll -> {
                val mBean = BalanceInfoManager.mBalanceInfoManager.getBalanceInfoBean()
                viewBinder.inputValue.setText("${mBean?.totalBalance}")

            }
        }
    }

    private fun showBuyingPop() {
        val mPop = PayingPassWordVerifyPop(_mActivity)
        XPopup.Builder(_mActivity)
            .setPopupCallback(object : SimpleCallback() {
                override fun onDismiss(popupView: BasePopupView?) {
                    super.onDismiss(popupView)
                    if (mPop.getIsOnVerifyPop()) {
                        if (mPop.getVerifyPop()) {
                            buyingCMLNow()
                        } else {
                            Toast.makeText(_mActivity, "支付密码错误", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            })
            .asCustom(mPop)
            .show()
    }

    private fun buyingCMLNow() {
        val uid= UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo?.uid ?: ""
        val map= mapOf(
            "buyNuums" to inputValue,
            "tokenType" to bean?.tokenType,
            "txid" to bean?.txid?.toString(),
            "uid" to uid
        )
         RestClient.builder()
             .raw(JSON.toJSONString(map))
             .url(R.string.saveCmlTxBuyOrder)
             .success {
                 saveCmlTxBuyOrder(it)
                 Toast.makeText(_mActivity, "购买成功", Toast.LENGTH_SHORT).show()
                 getUserBalanceInfo(_mActivity)
                 onBackPressedSupport()
             }
             .error { _, msg ->
                 Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
                 onBackPressedSupport()
             }.failure {
                 Toast.makeText(_mActivity, "购买失败", Toast.LENGTH_SHORT).show()
                 onBackPressedSupport()
             }
             .build().post()
    }

    @SuppressLint("RestrictedApi")
    private fun saveCmlTxBuyOrder(it: String?) {
        Log.d("saveCmlTxSellOrder", "saveCmlTxSellOrder== $it")
        val obj = JSON.parseObject(it)
        val pushMsg = obj["pushMsg"] ?: ""
        val txNo = obj["txNo"].toString()
        val mPushMsgBean = JSON.parseObject(JSON.toJSONString(pushMsg), PushMsgBean::class.java)

        ArchTaskExecutor.getIOThreadExecutor().execute {
            try {
                val deviceTokens = mPushMsgBean.deviceToken
                val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
                val pushHelper = PushHelper()
                mPushMsgBean.type = FAN_BI
                mPushMsgBean.orderId = txNo
                val broadcast = PushHelper.getAndroidBroadcast()
                broadcast.setTitle("出售${bean?.tokenType}")
                broadcast.setDeviceToken(deviceTokens)
                broadcast.setPlaySound(true)
                broadcast.setTicker("出售${bean?.tokenType}")
                broadcast.setCustomField(JSON.toJSONString(mPushMsgBean))
                broadcast.setTitle("${userInfo?.nickName} 向你出售 $inputValue 个 ${bean?.tokenType}")
                broadcast.setText("${userInfo?.nickName} 向你出售 $inputValue 个 ${bean?.tokenType}")

                pushHelper.sendAndroidBroadcast(broadcast)
            } catch (e: Exception) {
                e.printStackTrace()
            }


        }
    }

    private fun buyingSSTNow() {
        val uid= UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo?.uid ?: ""
        val map= mapOf(
            "buyNuums" to inputValue,
            "tokenType" to bean?.tokenType,
            "txid" to bean?.txid?.toString(),
            "uid" to uid
        )
        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.saveTxBuyOrder)
            .success {

                parseSaveTxBuyOrder(it)
            }
            .failure {
                Toast.makeText(_mActivity, "购买失败", Toast.LENGTH_SHORT).show()
                onBackPressedSupport()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
                onBackPressedSupport()
            }
            .build().post()
    }

    private fun parseSaveTxBuyOrder(it: String?) {
       val orderInfoBean = JSON.parseObject(it, CurrencyOrderInfoBean::class.java)
        startWithPop(CurrencyTransferBuyStatusFragment.newInstance(orderInfoBean))
    }

    @SuppressLint("SetTextI18n")
    override fun onTimer() {
        handler.post {
            timer--

            if (timer < 0) {
                stopTimer()
                onBackPressedSupport()
            }else{
                viewBinder.cancelTv.text = "${timer}秒后自动取消"
            }

        }
    }

    override fun onPause() {
        super.onPause()
        hideSoftInput()
    }

    override fun onDestroy() {
        super.onDestroy()
        stopTimer()
    }

    @SuppressLint("SetTextI18n")
    override fun afterTextChanged(s: Editable?, viewId: Int) {
        when (viewId) {
            R.id.inputValue -> {
                viewBinder.costMoney.text = ""
                if (!TextUtils.isEmpty(s.toString())) {
                    inputValue = s.toString()
                    viewBinder.costMoney.text = "$inputValue $sst"
                }

            }
        }
    }
}